//
//  LSWorkOvertimeListViewController.m
//  LaSaCivilAffairsDepartment
//
//  Created by 聂志康 on 2019/1/23.
//  Copyright © 2019 wpkj. All rights reserved.
//

#import "LSWorkOvertimeListViewController.h"
#import "LSAttendanceManagementTableViewCell.h"
#import "LSWorkOvertimeDetailViewController.h"

#define CountPerPage 10

@interface LSWorkOvertimeListViewController () <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) int tableViewPage;
@property (nonatomic, strong) NSMutableArray *dataArrayM;
@property (nonatomic, strong) NZKNoDataView *nodataView;
@property (nonatomic, strong) NZKNetworkErrorView *networkErrorView;
@end

static NSString *LSAttendanceManagementTableViewCellID = @"LSAttendanceManagementTableViewCellID";

@implementation LSWorkOvertimeListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"加班列表";
    [self loadData];
    [self.view addSubview:self.tableView];
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
}

- (void)loadData {
    self.tableViewPage = 1;
    NSDictionary *param = @{@"token":[ValidateUtils validateNull:[UserInfoModel sharedInstance].token],@"rows":[NSString stringWithFormat:@"%d",CountPerPage],@"page":[NSString stringWithFormat:@"%d",self.tableViewPage]};
    [NetworkUtils requestNOHandleWithMethod:@"POST" URL:WorkOvertimeList param:param completionHandler:^(id responseObject, NSError *connectionError) {
        self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        [self.tableView.mj_header endRefreshing];
        if (!connectionError) {
            NSArray *dataArray = [responseObject objectForKey:@"data"];
            if (dataArray && dataArray.count > 0) {
                [self.nodataView removeFromSuperview];
                [self.networkErrorView removeFromSuperview];
                self.dataArrayM = [[NSMutableArray alloc] initWithArray:dataArray];
                if (self.dataArrayM.count < self.tableViewPage*CountPerPage) {
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                }
                [self.tableView reloadData];
            } else {
                [self.dataArrayM removeAllObjects];
                [self.tableView reloadData];
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
                [self.networkErrorView removeFromSuperview];
                [self.tableView addSubview:self.nodataView];
            }
        } else {
            [self.nodataView removeFromSuperview];
            [self.tableView addSubview:self.networkErrorView];
            self.networkErrorView.tipText = [NSString stringWithFormat:@"%@",connectionError.localizedDescription];
        }
    }];
}

- (void)loadMoreData {
    self.tableViewPage++;
    NSDictionary *param = @{@"token":[ValidateUtils validateNull:[UserInfoModel sharedInstance].token],@"rows":[NSString stringWithFormat:@"%d",CountPerPage],@"page":[NSString stringWithFormat:@"%d",self.tableViewPage]};
    [NetworkUtils requestNOHandleWithMethod:@"POST" URL:WorkOvertimeList param:param completionHandler:^(id responseObject, NSError *connectionError) {
        if (!connectionError) {
            NSArray *dataArray = [responseObject objectForKey:@"data"];
            if (dataArray && dataArray.count > 0) {
                [self.dataArrayM addObjectsFromArray:dataArray];
                if (self.dataArrayM.count < self.tableViewPage*CountPerPage) {
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                } else {
                    [self.tableView.mj_footer endRefreshing];
                }
                [self.tableView reloadData];
            } else {
                self.tableViewPage--;
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        } else {
            self.tableViewPage--;
            [self.tableView.mj_footer endRefreshing];
            [MBProgressHUD showTipMessageInWindow:connectionError.localizedDescription];
        }
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArrayM.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LSAttendanceManagementTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LSAttendanceManagementTableViewCellID forIndexPath:indexPath];
    cell.mainTitleLabel.text = [ValidateUtils validateNull:self.dataArrayM[indexPath.row][@"createName"]];
    cell.mainSubtitleLabel.text = [ValidateUtils validateNull:self.dataArrayM[indexPath.row][@"sysOrgCode"]];
    NSString *timeStampString = [ValidateUtils validateNull:self.dataArrayM[indexPath.row][@"begintime"]];
    NSString *endTimeStampString = [ValidateUtils validateNull:self.dataArrayM[indexPath.row][@"endtime"]];
    // iOS 生成的时间戳是10位
    NSTimeInterval interval = [timeStampString doubleValue] / 1000.0;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
    NSTimeInterval endInterval = [endTimeStampString doubleValue] / 1000.0;
    NSDate *endDate = [NSDate dateWithTimeIntervalSince1970:endInterval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [formatter stringFromDate:date];
    NSString *endDateString = [formatter stringFromDate:endDate];
    cell.mainTimeLabel.text = [NSString stringWithFormat:@"%@ ~ %@",dateString,endDateString];
    NSNumber *state = self.dataArrayM[indexPath.row][@"bpmStatus"];
    switch (state.intValue) {
        case 1:
            cell.mainStatusLabel.text = @"待提交";
            break;
        case 2:
            cell.mainStatusLabel.text = @"审批中";
            break;
        case 3:
            cell.mainStatusLabel.text = @"已完成";
            break;
        default:
            break;
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return LSAttendanceManagementTableViewCellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    NSDictionary *dataDict = self.dataArrayM[indexPath.row];
    /*
     {
         begintime = 1573476115000;
         bpmStatus = 2;
         contactId = 8a8ab0b246dc81120146dc8181950052;
         createBy = admin;
         createDate = 1573474099000;
         createName = "孟婆";
         duration = 67;
         endtime = 1574167318000;
         id = 8a8a80866e596a09016e5a5d606d0016;
         isDeleted = 0;
         isNotice = 0;
         job = c;
         personNum = 6;
         realName = "孟婆";
         reason = "  ＋＋#@ __@………… ";
         sysCompanyCode = 5401;
         sysOrgCode = "拉萨市民政局";
     }
     */
    LSWorkOvertimeDetailViewController *workOvertimeDetailVC = [[LSWorkOvertimeDetailViewController alloc] init];
    workOvertimeDetailVC.tipTitleLabelArray = @[@"加班事由：",@"职务：",@"加班人数：",@"加班时长：",@"加班开始时间：",@"加班结束时间：",@"是否告知分管领导："];
    workOvertimeDetailVC.infoTitleLabelArray = @[@"reason",@"job",@"personNum",@"duration",@"begintime",@"endtime",@"isNotice"];
    workOvertimeDetailVC.responsObject = dataDict;
    [self.navigationController pushViewController:workOvertimeDetailVC animated:true];
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-SafeAreaTopHeight)];
        _tableView.separatorInset = UIEdgeInsetsZero;
        _tableView.separatorColor = hexColor(DDDDDD);
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = hexColor(EEEEEE);
        _tableView.tableFooterView = [UIView new];
        [_tableView registerClass:LSAttendanceManagementTableViewCell.class forCellReuseIdentifier:LSAttendanceManagementTableViewCellID];
    }
    return _tableView;
}

- (NSMutableArray<NSDictionary *> *)dataArrayM {
    if (!_dataArrayM) {
        _dataArrayM = [[NSMutableArray alloc] init];
    }
    return _dataArrayM;
}

- (NZKNoDataView *)nodataView {
    if (!_nodataView) {
        _nodataView = [[NZKNoDataView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-SafeAreaTopHeight) withTip:@"暂无相关信息" andButtonText:nil];
    }
    return _nodataView;
}

- (NZKNetworkErrorView *)networkErrorView {
    if (!_networkErrorView) {
        WS
        _networkErrorView = [[NZKNetworkErrorView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-SafeAreaTopHeight) withRefreshBlock:^{
            [weakSelf loadData];
        }];
    }
    return _networkErrorView;
}

@end
